#include "Database.h"


#include "_Global/Mysql/Mysql.h"
#include "_Global/GameCommon.h"


#include <QSqlQuery>
#include <QSqlRecord>

#include <QDir>



Database::Database()
{
    //bInited = false;
    m_pMysql = new Mysql;
    m_pMysql->moveToThread(m_pThread);
}
Database::~Database()
{
}

int Database::_init()
{
    LongTask::_init();

    //if(m_pMysql != nullptr)
    //    m_pMysql = new Mysql;

    return 0;
}
int Database::_release()
{
    m_pMysql->deleteLater();
    return LongTask::_release();
}


//!!!注意这里，游戏服务器和信息服务器要区分!!!
int Database::sl_QueryUser(QString userName, QString password, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    qDebug() << "[Database]queryUser in threadID:" << QThread::currentThreadId();

    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)INFO_SERVER_RESPONSE << (qint16)INFO_SERVER_CLIENT << (qint16)INFO_SERVER_CLIENT_LOGIN;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery = QString("SELECT * FROM lms_user_info WHERE login_name='%1'")
                .arg(userName);

        if(!query.exec(strQuery))
        {
            ret = -2;
            ds << (qint16)INFO_SERVER_CLIENT_LOGIN_FAIL
               << (qint16)ret;
            emit s_QueryUserFinished(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        //qDebug()<<query.record().count()<<query.size();
        //if(query.seek(0) == false)
        if(!query.next())
        {
            ret = 1;
            ds << (qint16)INFO_SERVER_CLIENT_LOGIN_FAIL
               << (qint16)ret;
            emit s_QueryUserFinished(socketContext, ret, "", ba);
            query.finish();
            return ret;
        }

        if(password == query.value("password").toString())
        {
            ret = 0;
            _GameUserData gud;
            gud.m_unID = query.value("id").toInt();
            gud.m_strUserName = query.value("login_name").toString();
            ////gud.m_unUserGameID = query.value("id").toInt();
            //gud.m_strNickName = query.value("nick_name").toString();
            //gud.m_nSex = query.value("sex").toInt();

            ds << (qint16)INFO_SERVER_CLIENT_LOGIN_SUCCESS
               << (quint32)(gud.m_unID)
               //<< (qint32)(socketContext.nSocketID)
               //<< (qint32)(gud.m_nGradeID)
                  ;
            emit s_QueryUserFinished(socketContext, ret, "", ba, gud);
            query.finish();
            return ret;
        }
        else
        {
            ret = 2;
            ds << (qint16)INFO_SERVER_CLIENT_LOGIN_FAIL
               << (qint16)ret;
            emit s_QueryUserFinished(socketContext, ret, "", ba);
            query.finish();
            return ret;
        }
        //pGameUserData->id = query.value("ID").toUInt();
        //user.Nick = query.value("Nick").toString();
        //query.finish();
        //m_db.close();
        //return true;
    }
    else
    {
        ret = -1;
        ds << (qint16)INFO_SERVER_CLIENT_LOGIN_FAIL
           << (qint16)ret;
        emit s_QueryUserFinished(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}

int Database::sl_RegisterUser(QString userName, QString password, qint16 sex, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)INFO_SERVER_RESPONSE << (qint16)INFO_SERVER_CLIENT << (qint16)INFO_SERVER_CLIENT_REGISTER;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询

        /*
        query.prepare("INSERT INTO UserInfo(username,nickname,password,sex) VALUES (?, ?, ?, ?)");

        QVariantList names,ages;
        names << "Tom" << "Jack" << "Jane" << "Jerry";
        ages << 20 << 23 << 22 << 25;

        //方法1:
        query.prepare("INSERT INTO User (Name, Nick, Pass) VALUES (?, ?, ?)");
        query.addBindValue(names);
        query.addBindValue(ages);

        //???不是不可以吗,要用QStringList???
        query.addBindValue(pGameUserData->m_strUserName);
        query.addBindValue(pGameUserData->m_strNickName);
        query.addBindValue(pGameUserData->password);
        query.addBindValue(pGameUserData->m_nSex);


        if (!query.execBatch())
        {
            qDebug()<<query.lastError().text();
            showError(query.lastError().text());
            return -2;
        }



        //方法2:好像不能用!?
        query.prepare("INSERT INTO User (name, age) VALUES (:name, :age)");
        //query.bindValue(":name", names);
        //query.bindValue(":age", ages);


        */



        /*/方法3:
        QString strQuery = QString("INSERT INTO lms_user_info(user_login,nick_name,password,sex) VALUES('%1','%2','%3',%4)")
                .arg(pGameUserData->m_strUserName)
                .arg(pGameUserData->m_strNickName)
                .arg(password.replace(QChar('\''),"\'\'"))
                .arg(pGameUserData->m_nSex);
        if(!query.exec(strQuery))
        {
            if(query.lastError().number() == 1062)  //重复
            {
                query.finish();
                return 1;
            }
            Critical(getDB()->lastError().text());
            Critical(query.lastError().text());
            Critical(strQuery);
            query.finish();
            return -2;
        }
        query.finish();*/


        //方法4:
        QString strQuery = QString("SELECT RegisterUser('%1','%2',%3) as ID")
                .arg(userName)
                .arg(password.replace(QChar('\''),"\'\'"))
                .arg(sex)
                ;
        if(!query.exec(strQuery))
        {
            //qDebug() << "[!sl_RegisterUser]sl_RegisterUser" << query.lastError() << query.lastError().number() << query.lastError().nativeErrorCode();
            if(query.lastError().number() == 1062)  //错误
            {
                //qDebug() << "!!!!!!!!!1062-1" << query.lastInsertId() << query.size() << query.record() << query.record().count();
                ret = 1;
                ds << (qint16)INFO_SERVER_CLIENT_REGISTER_FAIL << (qint16)ret;
                emit s_RegisterUserFinished(socketContext, ret
                                            , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                                            , ba);
                query.finish();
                return ret;
            }
            else
            {
                ret = -2;
                ds << (qint16)INFO_SERVER_CLIENT_REGISTER_FAIL << (qint16)ret;
                emit s_RegisterUserFinished(socketContext, ret
                                 , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                                 , ba);
                query.finish();
                return ret;
            }
        }
        if(!query.next())
        {
            ret = -3;
            ds << (qint16)INFO_SERVER_CLIENT_REGISTER_FAIL << (qint16)ret;
            emit s_RegisterUserFinished(socketContext, ret
                                        , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                                        , ba);
            query.finish();
            return ret;
        }

        _GameUserData gud;
        gud.m_unID = query.value("ID").toInt();
        gud.m_strUserName = userName;
        //gud.m_strNickName = nickName;
        //gud.m_nSex = sex;
        ////gud.m_unUserGameID = query.value("ID").toInt();
        ////gud.m_nScore = query.value("Score").toInt();

        ret = 0;
        ds << (qint16)INFO_SERVER_CLIENT_REGISTER_SUCCESS << (quint32)gud.m_unID;// << (qint32)socketContext.nSocketID;
        emit s_RegisterUserFinished(socketContext, ret, "", ba, gud);
        query.finish();

        //qDebug()<<query.record().count()<<query.size();
        //m_db.close();
        return ret;
    }
    else
    {
        ret = -1;
        ds <<(qint16)INFO_SERVER_CLIENT_REGISTER_FAIL << (qint16)ret;
        emit s_RegisterUserFinished(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}


int Database::sl_GetGameServerInfoToBuffer(QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)INFO_SERVER_RESPONSE << (qint16)INFO_SERVER_CLIENT << (qint16)INFO_SERVER_CLIENT_SERVERINFO;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery = QString("SELECT * FROM lms_game_server_info");

        if(!query.exec(strQuery))
        {
            ret = -2;
            //Debug_Leamus("Query UserInfo ERROR");
            ds << (qint16)INFO_SERVER_CLIENT_SERVERINFO_FAIL << (qint16)ret;
            emit s_GetGameServerInfoToBufferFinished(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        ret = 0;
        ds << (qint16)INFO_SERVER_CLIENT_SERVERINFO_SUCCESS;

        qint16 ServerCount = 0;
        int pos = ds.device()->pos();
        ds << ServerCount;
        while(query.next())
        {
            ds << (quint32)(query.value("ID").toUInt());
            ds << query.value("Name").toString();
            ds << query.value("IP").toString();
            ds << (quint16)(query.value("Port").toUInt());
            ds << query.value("Key").toString();
            ServerCount++;
            //m_GameServiceInfoList.append(QVariant::fromValue<_GameServiceInfo*>(pGameInfo));
            //m_GameServiceInfoList.insert(query.value("ID").toString(),QVariant::fromValue<ClassInfo*>(cInfo));
        }
        ds.device()->seek(pos);
        ds << ServerCount;

        emit s_GetGameServerInfoToBufferFinished(socketContext, ret, "", ba
                         );

        query.finish();
        return ret;
    }
    else
    {
        ret = -1;
        ds << (qint16)INFO_SERVER_CLIENT_SERVERINFO_FAIL << (qint16)ret;
        emit s_GetGameServerInfoToBufferFinished(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}


int Database::sl_GetGameUserInfoToBuffer(quint32 userID, qint32 serverID, QString serverKey, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)GAME_SERVER_RESPONSE << (qint16)GAME_SERVER_CLIENT << (qint16)GAME_SERVER_CLIENT_GAMEUSERINFO;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery = QString("SELECT * FROM lms_game_user_info WHERE userid=%1 AND serverid=%2 AND serverid IN (SELECT ID FROM lms_game_server_info WHERE `key` = '%3')")
                .arg(userID)
                .arg(serverID)
                .arg(serverKey);

        if(!query.exec(strQuery))
        {
            ret = -2;
            //Debug_Leamus("Query UserInfo ERROR");
            ds << (qint16)GAME_SERVER_CLIENT_GAMEUSERINFO_FAIL << (qint16)ret;
            emit s_GetGameUserInfoToBufferFinished(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        if(!query.next())
        {
            ret = 1;
            ds << (qint16)GAME_SERVER_CLIENT_GAMEUSERINFO_FAIL << (qint16)ret;
            emit s_GetGameUserInfoToBufferFinished(socketContext, ret
                             , QString("[DataBase]没有此GameUserInfo:%1,%2").arg(userID).arg(serverID)
                             , ba
                             );
            query.finish();
            return ret;
        }


        _GameUserData gud;
        //gud.m_unID = userID;
        gud.m_unUserGameID = query.value("id").toInt();
        gud.m_strNickName = query.value("nick_name").toString();
        gud.m_nSex = query.value("sex").toInt();
        gud.m_nScore = query.value("score").toInt();
        gud.m_vExtraData = query.value("extern_data");

        //m_GameServiceUserInfo.tools.canReview = query.value("").to;
        //m_GameServiceUserInfo.tools.flagCorrectAnswer = query.value("").to;
        qDebug() << "[DataBase]GameUserInfo存在:" << gud.m_unUserGameID << gud.m_strNickName;

        ds << (qint16)GAME_SERVER_CLIENT_GAMEUSERINFO_SUCCESS;
        ds << (quint32)gud.m_unUserGameID;
        ds << gud.m_strNickName;
        ds << (qint16)gud.m_nSex;
        ds << (qint32)gud.m_nScore;
        ds << gud.m_vExtraData;

        ret = 0;
        emit s_GetGameUserInfoToBufferFinished(socketContext, ret, "", ba, gud);
        query.finish();
        return ret;


        /*/查询2种积分统计
        strQuery = QString("SELECT ScoreTotal,Type FROM lms_game_user_ranking WHERE usergameid=%1 AND serverid=%2 AND gradeid=%3 ORDER BY Type ASC")
                .arg(gud.m_unUserGameID)
                .arg(serverID)
                .arg(gradeID);

        if(!query.exec(strQuery))
        {
            ret = -3;
            ds << (qint16)GAME_SERVER_CLIENT_GAMEUSERINFO_FAIL << (qint16)ret;
            emit s_GetGameUserInfoToBufferFinished(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        qint32 scoreArray[2] = {0,0};
        while(query.next())
        {
            switch(query.value("Type").toInt())
            {
            case 1:
                scoreArray[0] = (qint32)query.value("ScoreTotal").toInt();
                break;
            case 2:
                scoreArray[1] = (qint32)query.value("ScoreTotal").toInt();
                break;
            default:
                break;
            }
        }


        ds << (qint16)GAME_SERVER_CLIENT_GAMEUSERINFO_SUCCESS;
        ds << (quint32)gud.m_unUserGameID;
        ds << gud.m_strNickName;
        ds << (qint16)gud.m_nSex;
        ds << (qint32)gud.m_nScore;
        ds << scoreArray[0];
        ds << scoreArray[1];

        ret = 0;
        emit s_GetGameUserInfoToBufferFinished(socketContext, ret, "", ba, gud);
        query.finish();
        return ret;
        */
    }
    else
    {
        ret = -1;
        ds << (qint16)GAME_SERVER_CLIENT_GAMEUSERINFO_FAIL << (qint16)ret;
        emit s_GetGameUserInfoToBufferFinished(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}



int Database::sl_RegisterGameUser(quint32 userID, qint32 serverID, QString nickName, qint16 sex, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)GAME_SERVER_RESPONSE << (qint16)GAME_SERVER_CLIENT << (qint16)GAME_SERVER_CLIENT_REGISTERGAMEUSERINFO;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery = QString("SELECT RegisterGameUser(%1,%2,'%3',%4) as ID")
                .arg(userID)
                .arg(serverID)
                .arg(nickName.replace(QChar('\''),""))
                .arg(sex)
                ;

        if(!query.exec(strQuery))
        {
            if(query.lastError().number() == 1062)  //错误
            {
                //qDebug() << "!!!!!!!!!1062-2" << query.lastInsertId() << query.size() << query.record() << query.record().count();
                ret = 1;
                ds << (qint16)GAME_SERVER_CLIENT_REGISTERGAMEUSERINFO_FAIL << (qint16)ret;
                emit s_RegisterGameUserFinished(socketContext, ret
                                 , "RegGameUserInfo重复", ba);
                query.finish();
                return ret;
            }

            ret = -2;
            ds << (qint16)GAME_SERVER_CLIENT_REGISTERGAMEUSERINFO_FAIL << (qint16)ret;
            emit s_RegisterGameUserFinished(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        if(!query.next())
        {
            ret = -3;
            ds << (qint16)GAME_SERVER_CLIENT_REGISTERGAMEUSERINFO_FAIL <<(qint16)ret;
            emit s_RegisterGameUserFinished(socketContext, ret
                             , "RegisterGameUser ERROR!", ba);
            query.finish();
            return ret;
        }

        _GameUserData gud;
        gud.m_unID = userID;
        gud.m_unUserGameID = query.value("ID").toInt();
        gud.m_strNickName = nickName;
        gud.m_nSex = sex;


        ret = 0;
        ds << (qint16)GAME_SERVER_CLIENT_REGISTERGAMEUSERINFO_SUCCESS << (quint32)gud.m_unUserGameID;
        emit s_RegisterGameUserFinished(socketContext, ret , "", ba, gud);
        query.finish();
        return ret;

/*
        //已经注册
        if(query.next())
        {
            query.finish();
            return 1;
        }

        query.finish();



        //添加昵称Record
        strQuery = strlistSqlQuery[10]
                .arg(userID).arg(serverID).arg(nickName).arg(sex);
        if(!query.exec(strQuery))
        {
            emit s_Critical(getDB()->lastError().text());
            emit s_Critical(query.lastError().text());
            emit s_Critical(strQuery);
            query.finish();
            return -3;
        }
        query.finish();


        strQuery = strlistSqlQuery[4]
                .arg(nickName);

        if(!query.exec(strQuery))
        {
            emit s_Critical(getDB()->lastError().text());
            emit s_Critical(query.lastError().text());
            emit s_Critical(strQuery);
            query.finish();
            return -4;
        }

        if(query.next())
        {
            _GameUserData* pGameUserData = (_GameUserData*)pClientInfo->m_pClientExtraData;
            pGameUserData->m_unUserGameID = query.value("ID").toInt();
            pGameUserData->m_strNickName = nickName;
            pGameUserData->m_nSex = sex;

            ds << (qint16)GAME_SERVER_CLIENT_REGISTERGAMEUSERINFO_SUCCESS
              << (quint32)query.value("ID").toUInt();
            query.finish();
            return 0;
        }
        else
        {
            query.finish();
            return -5;
        }
        */

        /*/*
        ////添加经验Record
        sql = QString("INSERT INTO GameUserScoreInfo(usergameid,score) VALUES(%1,0)").arg(m_LoginInfo.id);
        if(!query.exec(sql))
        {
            emit s_Critical(getDB()->lastError().text());
            emit s_Critical(query.lastError().text());
            emit s_Critical(strQuery);
            query.finish();
            return -1;
        }
        query.finish();* /*/
    }
    else
    {
        ret = -1;
        ds << (qint16)GAME_SERVER_CLIENT_REGISTERGAMEUSERINFO_FAIL <<(qint16)ret;
        emit s_RegisterGameUserFinished(socketContext, ret
                         , "[!Database]connectDB Error!", ba);
        return ret;
    }
}


int Database::sl_SetClientShareExtraGameData(quint32 userGameID, QString key, QVariant data, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)GAME_SERVER_RESPONSE << (qint16)GAME_SERVER_CLIENT << (qint16)GAME_SERVER_CLIENT_SHAREEXTRAGAMEDATA_SET;

    //qDebug() << "[Database]Setting GameData:" << data << userGameID;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery;

        if(data.canConvert<QVariantMap>())
        {
            if(key.isEmpty())
                strQuery = QString("UPDATE lms_game_user_info SET extern_data = cast(? AS JSON) WHERE id=%1;")
                        .arg(key);
            else
            {
                strQuery = QString("UPDATE lms_game_user_info SET extern_data = JSON_SET(IFNULL(extern_data,'{}'), \"%1\", cast(? AS JSON)) WHERE id=%2;")
                //strQuery = QString("UPDATE lms_game_user_info SET extern_data = CASE WHEN extern_data IS NULL THEN '{}' ELSE (JSON_SET(extern_data, \"%1\", cast(? AS JSON))) END WHERE id=%2;")
                        .arg(key)
                        //.arg(JSon2String(data))
                        .arg(userGameID);
            }

            query.prepare(strQuery);
            query.addBindValue(QVariantList() << JSon2String(data));
        }
        else if(data.canConvert<QVariantList>())
        {
            if(key.isEmpty())
                strQuery = QString("UPDATE lms_game_user_info SET extern_data = cast(? AS JSON) WHERE id=%1;")
                        .arg(key);
            else
            {
                strQuery = QString("UPDATE lms_game_user_info SET extern_data = JSON_SET(IFNULL(extern_data,'{}'), \"%1\", cast(? AS JSON)) WHERE id=%2;")
                //strQuery = QString("UPDATE lms_game_user_info SET extern_data = CASE WHEN extern_data IS NULL THEN '{}' ELSE (JSON_SET(extern_data, \"%1\", cast(? AS JSON))) END WHERE id=%2;")
                        .arg(key)
                        .arg(userGameID);
            }

            query.prepare(strQuery);
            query.addBindValue(QVariantList() << JSon2String(data));
        }
        else
        {
            if(key.isEmpty())
                strQuery = QString("UPDATE lms_game_user_info SET extern_data = cast(? AS JSON) WHERE id=%1;")
                        .arg(key);
            else
            {
                strQuery = QString("UPDATE lms_game_user_info SET extern_data = JSON_SET(IFNULL(extern_data,'{}'), \"%1\", ?) WHERE id=%2")
                //strQuery = QString("UPDATE lms_game_user_info SET extern_data = CASE WHEN extern_data IS NULL THEN '{}' ELSE (JSON_SET(extern_data, \"%1\", ?)) END WHERE id=%2;")
                        .arg(key)
                        .arg(userGameID);
            }

            query.prepare(strQuery);
            query.addBindValue(QVariantList() << data);
        }

        if(!query.execBatch())
        {
            ret = -2;
            ds << (qint16)GAME_SERVER_CLIENT_SHAREEXTRAGAMEDATA_SET_FAIL
               << (qint16)ret;
            emit s_SetClientShareExtraGameData(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        /*
        if(!query.exec())
        {
            ret = -2;
            ds << (qint16)GAME_SERVER_CLIENT_SHAREEXTRAGAMEDATA_SET_FAIL
               << (qint16)ret;
            emit s_SetClientShareExtraGameData(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery + "\r\n\r\n" + query.lastQuery() + "\r\n\r\n" + query.executedQuery()
                             , ba
                             );
            query.finish();
            return ret;
        }*/

        ds << (qint16)GAME_SERVER_CLIENT_SHAREEXTRAGAMEDATA_SET_SUCCESS;

        qDebug() << "[Database]Set GameData:" << query.numRowsAffected();
        qDebug() << "------------------";


        ret = 0;
        emit s_SetClientShareExtraGameData(socketContext, ret, "", ba);
        query.finish();
        return ret;
    }
    else
    {
        ret = -1;
        ds << (qint16)GAME_SERVER_CLIENT_SHAREEXTRAGAMEDATA_SET_FAIL << (qint16)ret;
        emit s_SetClientShareExtraGameData(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}



int Database::sl_InsertUserOnlineLog(quint32 userGameID, qint16 clientType, quint32 ip, quint16 port, QDateTime dtLogin, QDateTime dtLogout)
{
    //qDebug()<<"insertUserOnlineLog";

    int ret;
    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery;

        strQuery = QString("INSERT INTO lms_game_user_onlineLog(UserGameID,client_type,client_ip,login_datetime,logout_datetime) VALUES(%1,%2,%3,'%4','%5');")
                .arg(userGameID)
                .arg(clientType)
                .arg(ip)
                .arg(dtLogin.toString("yyyy-MM-dd hh:mm:ss"))
                .arg(dtLogout.toString("yyyy-MM-dd hh:mm:ss"));

        if(!query.exec(strQuery))
        {
            ret = -2;
            emit s_Critical(ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             );
            query.finish();
            return ret;
        }

        qDebug() << "[Database]sl_InsertUserOnlineLog:" << ip << port;

        ret = 0;
        query.finish();
        return ret;
    }
    else
    {
        ret = -1;
        emit s_Critical(ret, "[!Database]connectDB Error!");
        return ret;
    }
}





int Database::sl_GetClientGameData(quint32 userGameID, qint32 dataType, qint32 dataValue, QString key, qint32 operationID, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)GAME_SERVER_RESPONSE << (qint16)GAME_SERVER_CLIENT << (qint16)GAME_SERVER_GETDATA << dataType << dataValue << operationID;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery;

        switch(dataType)
        {
        case _Common::DataType_JSon_Info:
            if(key.isEmpty())
                strQuery = QString("SELECT `data` FROM lms_game_info_json WHERE user_game_id=%1 AND data_value=%2")
                        .arg(userGameID).arg(dataValue);
            else
                strQuery = QString("SELECT JSON_EXTRACT(`data`, '%1') AS `data` FROM lms_game_info_json WHERE user_game_id=%2 AND data_value=%3")
                        .arg(key).arg(userGameID).arg(dataValue);

            break;
        case _Common::DataType_Binary_Info:
            strQuery = QString("SELECT `data` FROM lms_game_info_binary WHERE user_game_id=%1 AND data_value=%2")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_Blob_Info:
            strQuery = QString("SELECT `data` FROM lms_game_info_blob WHERE user_game_id=%1 AND data_value=%2")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_JSon_Data:
            if(key.isEmpty())
                strQuery = QString("SELECT `data` FROM lms_game_data_json WHERE user_game_id=%1 AND data_value=%2")
                        .arg(userGameID).arg(dataValue);
            else
                strQuery = QString("SELECT JSON_EXTRACT(`data`, '%1') AS `data` FROM lms_game_data_json WHERE user_game_id=%2 AND data_value=%3")
                        .arg(key).arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_File_Info:
            {
                QString fileName = QString("Uploads/%1/%2").arg(dataValue).arg(userGameID);
                QFile file(fileName);
                if(!file.open(QIODevice::ReadOnly))
                {
                    ret = -3;
                    ds << (qint16)GAME_SERVER_GETDATA_FAIL
                       << (qint16)ret;
                    emit s_GetClientGameData(socketContext, ret
                                     , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                                     , ba
                                     );
                    return ret;
                }

                ret = 0;
                ds << (qint16)GAME_SERVER_GETDATA_SUCCESS
                   << file.readAll();
                file.close();
                emit s_GetClientGameData(socketContext, ret
                                 , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                                 , ba
                                 );
                query.finish();
                return ret;

                /*strQuery = QString("SELECT `data` FROM lms_game_info_file WHERE user_game_id=%1 AND data_value=%2")
                        .arg(userGameID).arg(dataValue);*/
            }
            break;

        default:
            emit s_Critical(dataType, tr("[!Database]Get Datatype Error"));
            break;
        }


        if(!query.exec(strQuery))
        {
            ret = -2;
            ds << (qint16)GAME_SERVER_GETDATA_FAIL
               << (qint16)ret;
            emit s_GetClientGameData(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        if(!query.next())
        {
            ret = 0;
            ds << (qint16)GAME_SERVER_GETDATA_FAIL
               << (qint16)ret;
            emit s_GetClientGameData(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }
        QVariantList listData;
        do
        {
            listData << query.value("data");
        }while(query.next());


        //out << (quint32)query.value("WordCount").toUInt();
        //recordCount ++;

        ds << (qint16)GAME_SERVER_GETDATA_SUCCESS << listData;



        qDebug() << "[Database]Get:" << query.numRowsAffected() << listData;
        qDebug() << "------------------";


        ret = listData.length();
        emit s_GetClientGameData(socketContext, ret, "", ba);
        query.finish();
        return ret;
    }
    else
    {
        ret = -1;
        ds << (qint16)GAME_SERVER_GETDATA_FAIL << (qint16)ret;
        emit s_GetClientGameData(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}

int Database::sl_SetClientGameData(quint32 userGameID, qint32 dataType, qint32 dataValue, QString key, QVariant data, qint32 operationID, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)GAME_SERVER_RESPONSE << (qint16)GAME_SERVER_CLIENT << (qint16)GAME_SERVER_SETDATA << dataType << dataValue << operationID;

    qDebug() << "[Database]Setting:" << data << userGameID << dataType << dataValue;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery;

        switch(dataType)
        {
        case _Common::DataType_JSon_Info:
            if(key.isEmpty())
            {
                strQuery = QString("INSERT INTO lms_game_info_json(user_game_id, data_value, `data`) VALUES (%1, %2, cast(? AS JSON)) ON DUPLICATE KEY UPDATE `data` = VALUES(data);")
                        .arg(userGameID).arg(dataValue);
            }
            else
            {
                //strQuery = QString("INSERT INTO lms_game_info_json(user_game_id, data_value, `data`) VALUES (%1, %2, ?) ON DUPLICATE KEY UPDATE data = VALUES(data);")
                strQuery = QString("INSERT INTO lms_game_info_json(user_game_id, data_value, `data`) VALUES (%1, %2, cast('{}' AS JSON)) ON DUPLICATE KEY UPDATE `data` = JSON_SET(IFNULL(`data`,'{}'), '%3', cast(? AS JSON));")
                        .arg(userGameID).arg(dataValue).arg(key);
            }
            break;
        case _Common::DataType_Binary_Info:
            strQuery = QString("INSERT INTO lms_game_info_binary(user_game_id, data_value, data) VALUES (%1, %2, ?) ON DUPLICATE KEY UPDATE data = VALUES(data);")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_Blob_Info:
            strQuery = QString("INSERT INTO lms_game_info_blob(user_game_id, data_value, data) VALUES (%1, %2, ?) ON DUPLICATE KEY UPDATE data = VALUES(data);")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_JSon_Data:
            if(key.isEmpty())
            {
                strQuery = QString("INSERT INTO lms_game_data_json(user_game_id, data_value, `data`) VALUES (%1, %2, cast(? AS JSON)) ON DUPLICATE KEY UPDATE `data` = VALUES(data);")
                        .arg(userGameID).arg(dataValue);
            }
            else
            {
                //strQuery = QString("INSERT INTO lms_game_data_json(user_game_id, data_value, data) VALUES (%1, %2, ?) ON DUPLICATE KEY UPDATE data = VALUES(data);")
                strQuery = QString("INSERT INTO lms_game_data_json(user_game_id, data_value, `data`) VALUES (%1, %2, cast('{}' AS JSON)) ON DUPLICATE KEY UPDATE `data` = JSON_SET(IFNULL(`data`,'{}'), '%3', cast(? AS JSON));")
                        .arg(userGameID).arg(dataValue).arg(key);
            }
            break;
        case _Common::DataType_File_Info:
            {
                QString fileName = QString("Uploads/%1/%2").arg(dataValue).arg(userGameID);
                QDir dir(QFileInfo(fileName).absolutePath());
                //QDir dir(QString("%d/%s").arg(dataValue).arg(QDate().currentDate().toString("yyyy-MM-dd")));
                if(!dir.exists())    /**< 如果目标目录不存在，则进行创建 */
                    if(!dir.mkpath(dir.absolutePath()))
                    {
                        ret = -5;
                        ds << (qint16)GAME_SERVER_SETDATA_FAIL
                           << (qint16)ret;
                        emit s_SetClientGameData(socketContext, ret
                                         , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                                         , ba
                                         );
                        return ret;
                    }

                QFile file(fileName);
                if(!file.open(QIODevice::WriteOnly))
                {
                    ret = -6;
                    ds << (qint16)GAME_SERVER_SETDATA_FAIL
                       << (qint16)ret;
                    emit s_SetClientGameData(socketContext, ret
                                     , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                                     , ba
                                     );
                    return ret;
                }

                QDataStream dsFile(&file);
                dsFile << data;
                //ds << QThread::currentThreadId();

                file.flush();
                //dsFile.setDevice(nullptr);
                file.close();


                ret = 0;
                ds << (qint16)GAME_SERVER_SETDATA_SUCCESS
                   << (qint16)ret;
                emit s_SetClientGameData(socketContext, ret
                                 , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                                 , ba
                                 );
                return ret;

                /*strQuery = QString("SELECT `data` FROM lms_game_info_file WHERE user_game_id=%1 AND data_value=%2")
                        .arg(userGameID).arg(dataValue);*/
            }
            break;

        default:
            emit s_Critical(dataType, tr("[!Database]Set Datatype Error"));
            break;
        }

        query.prepare(strQuery);

        QVariantList d;
        d << data;

        //query.bindValue(":data", d);
        query.addBindValue(d);

        if(!query.execBatch())
        {
            qCritical() << "[!Database]Set Data ERROR:" << d;
            ret = -2;
            ds << (qint16)GAME_SERVER_SETDATA_FAIL
               << (qint16)ret;
            emit s_SetClientGameData(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        //qDebug() << "[Database]Setted:" << query.numRowsAffected();
        //qDebug() << "------------------";

        switch (query.numRowsAffected()) {
        case 0:     //更新(0表示和原来的值相同)
            ret = 0;
            ds << (qint16)GAME_SERVER_SETDATA_SUCCESS << (qint16)ret;
            emit s_SetClientGameData(socketContext, ret, "Set(No Update)", ba);
            query.finish();
            return ret;
        case 2:     //更新
            ret = 2;
            ds << (qint16)GAME_SERVER_SETDATA_SUCCESS << (qint16)ret;
            emit s_SetClientGameData(socketContext, ret, "Set(Update)", ba);
            query.finish();
            return ret;
        case 1:     //插入
            ret = 1;
            ds << (qint16)GAME_SERVER_SETDATA_SUCCESS << (qint16)ret;
            emit s_SetClientGameData(socketContext, ret, "Set(Insert)", ba);
            query.finish();
            return ret;
        default:
            ret = -3;
            ds << (qint16)GAME_SERVER_SETDATA_FAIL << (qint16)ret;
            emit s_SetClientGameData(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            //emit s_SetClientGameData(socketContext, ret, "[!Database]CALL SetClientData ERROR!", ba);
            query.finish();
            return ret;
        }

    }
    else
    {
        ret = -1;
        ds << (qint16)GAME_SERVER_SETDATA_FAIL << (qint16)ret;
        emit s_SetClientGameData(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}

int Database::sl_DeleteClientGameData(quint32 userGameID, qint32 dataType, qint32 dataValue, qint32 operationID, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)GAME_SERVER_RESPONSE << (qint16)GAME_SERVER_CLIENT << (qint16)GAME_SERVER_DELETEDATA << dataType << dataValue << operationID;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery;

        switch(dataType)
        {
        case _Common::DataType_JSon_Info:
            strQuery = QString("DELETE FROM lms_game_info_json WHERE user_game_id=%1 AND data_value=%2")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_Binary_Info:
            strQuery = QString("DELETE FROM lms_game_info_binary WHERE user_game_id=%1 AND data_value=%2")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_Blob_Info:
            strQuery = QString("DELETE FROM lms_game_info_blob WHERE user_game_id=%1 AND data_value=%2")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_JSon_Data:
            if(dataValue == -1)
                strQuery = QString("DELETE FROM lms_game_data_json WHERE user_game_id=%1")
                        .arg(userGameID);
            else
                strQuery = QString("DELETE FROM lms_game_data_json WHERE user_game_id=%1 AND data_value=%2")
                        .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_File_Info:
            {
                QString fileName = QString("Uploads/%1/%2").arg(dataValue).arg(userGameID);
                if(!QFile::exists(fileName))
                {
                    ret = -4;
                    ds << (qint16)GAME_SERVER_DELETEDATA_FAIL
                       << (qint16)ret;
                    emit s_DeleteClientGameData(socketContext, ret
                                     , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                                     , ba
                                     );
                    return ret;
                }
                else
                {
                    if(!QFile::remove(fileName))
                    {
                        ret = -5;
                        ds << (qint16)GAME_SERVER_DELETEDATA_FAIL
                           << (qint16)ret;
                        emit s_DeleteClientGameData(socketContext, ret
                                         , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                                         , ba
                                         );
                        return ret;
                    }

                    ds << (qint16)GAME_SERVER_DELETEDATA_SUCCESS;
                    ret = 0;
                    emit s_DeleteClientGameData(socketContext, ret, "", ba);
                    return ret;
                }
            }
            break;
        default:
            emit s_Critical(dataType, tr("[!Database]Delete Datatype Error"));
            break;
        }


        if(!query.exec(strQuery))
        {
            ret = -2;
            ds << (qint16)GAME_SERVER_DELETEDATA_FAIL
               << (qint16)ret;
            emit s_DeleteClientGameData(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        ds << (qint16)GAME_SERVER_DELETEDATA_SUCCESS;



        qDebug() << "[Database]Delete:" << query.numRowsAffected();
        qDebug() << "------------------";


        ret = 0;
        emit s_DeleteClientGameData(socketContext, ret, "", ba);
        query.finish();
        return ret;
    }
    else
    {
        ret = -1;
        ds << (qint16)GAME_SERVER_DELETEDATA_FAIL << (qint16)ret;
        emit s_DeleteClientGameData(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}



int Database::sl_InsertClientData(quint32 userGameID, qint32 dataType, qint32 dataValue, QVariant data, qint32 operationID, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)GAME_SERVER_RESPONSE << (qint16)GAME_SERVER_CLIENT << (qint16)GAME_SERVER_INSERTDATA << dataType << dataValue << operationID;

    qDebug() << "[Database]Inserting:" << data << userGameID << dataType << dataValue;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery;

        switch(dataType)
        {
        case _Common::DataType_JSon_Info:
            strQuery = QString("INSERT INTO lms_game_info_json(user_game_id, data_value, data) VALUES (%1, %2, ?)")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_Binary_Info:
            strQuery = QString("INSERT INTO lms_game_info_binary(user_game_id, data_value, data) VALUES (%1, %2, ?)")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_Blob_Info:
            strQuery = QString("INSERT INTO lms_game_info_blob(user_game_id, data_value, data) VALUES (%1, %2, ?)")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_JSon_Data:
            strQuery = QString("INSERT INTO lms_game_data_json(user_game_id, data_value, data) VALUES (%1, %2, ?)")
                    .arg(userGameID).arg(dataValue);
            break;
        default:
            emit s_Critical(dataType, tr("[!Database]Insert Datatype Error"));
            break;
        }

        query.prepare(strQuery);

        QVariantList d;
        d << data;

        query.addBindValue(d);

        if(!query.execBatch())
        {
            ret = -2;
            ds << (qint16)GAME_SERVER_INSERTDATA_FAIL
               << (qint16)ret;
            emit s_InsertClientData(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        ds << (qint16)GAME_SERVER_INSERTDATA_SUCCESS;

        qDebug() << "[Database]Inserted:" << query.numRowsAffected();
        qDebug() << "------------------";


        ret = 0;
        emit s_InsertClientData(socketContext, ret, "", ba);
        query.finish();
        return ret;
    }
    else
    {
        ret = -1;
        ds << (qint16)GAME_SERVER_INSERTDATA_FAIL << (qint16)ret;
        emit s_InsertClientData(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}
int Database::sl_UpdateClientData(quint32 userGameID, qint32 dataType, qint32 dataValue, QVariant data, qint32 operationID, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)GAME_SERVER_RESPONSE << (qint16)GAME_SERVER_CLIENT << (qint16)GAME_SERVER_UPDATEDATA << dataType << dataValue << operationID;

    qDebug() << "[Database]Updating:" << data << userGameID << dataType << dataValue;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery;

        switch(dataType)
        {
        case _Common::DataType_JSon_Info:
            strQuery = QString("UPDATE lms_game_info_json SET data=:data WHERE user_game_id=%1 AND data_value=%2;")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_Binary_Info:
            strQuery = QString("UPDATE lms_game_info_binary SET data=:data WHERE user_game_id=%1 AND data_value=%2;")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_Blob_Info:
            strQuery = QString("UPDATE lms_game_info_blob SET data=:data WHERE user_game_id=%1 AND data_value=%2;")
                    .arg(userGameID).arg(dataValue);
            break;
        case _Common::DataType_JSon_Data:
            strQuery = QString("UPDATE lms_game_data_json SET data=:data WHERE user_game_id=%1 AND data_value=%2;")
                    .arg(userGameID).arg(dataValue);
            break;
        default:
            emit s_Critical(dataType, tr("[!Database]Update Datatype Error"));
            break;
        }

        query.prepare(strQuery);

        QVariantList d;
        d << data;

        query.bindValue(":data", d);
        //query.addBindValue(d);

        if(!query.execBatch())
        {
            ret = -2;
            ds << (qint16)GAME_SERVER_UPDATEDATA_FAIL
               << (qint16)ret;
            emit s_UpdateClientData(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        ds << (qint16)GAME_SERVER_UPDATEDATA_SUCCESS;

        qDebug() << "[Database]Updated:" << query.numRowsAffected();
        qDebug() << "------------------";


        ret = 0;
        emit s_UpdateClientData(socketContext, ret, "", ba);
        query.finish();
        return ret;
    }
    else
    {
        ret = -1;
        ds << (qint16)GAME_SERVER_UPDATEDATA_FAIL << (qint16)ret;
        emit s_UpdateClientData(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}



int Database::sl_DBQuery(qint32 dataValue, QString strQuery, qint32 operationID, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    qDebug() << "[GameServer]queryUser in threadID:" << QThread::currentThreadId();

    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)GAME_SERVER_RESPONSE << (qint16)GAME_SERVER_CLIENT << (qint16)GAME_SERVER_DBQUERY << dataValue << operationID;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询

        if(!query.exec(strQuery))
        {
            ret = -2;
            ds << (qint16)GAME_SERVER_DBQUERY_FAIL
               << (qint16)ret;
            emit s_DBQuery(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        //qDebug()<<query.record().count()<<query.size();
        //if(query.seek(0) == false)
        /*if(!query.next())
        {
            ret = 1;
            ds << (qint16)GAME_SERVER_DBQUERY_FAIL
               << (qint16)ret;
            emit s_DBQuery(socketContext, ret, "", ba);
            query.finish();
            return ret;
        }*/

        QVariantList list;
        while(query.next())
        {
            for(int i = 0; i < query.record().count(); i++)
            {
                list << query.value(i);
            }
        }

        //qDebug() << "!!!!!!!!!query" << query.lastInsertId() << query.size() << query.record() << query.record().count();


        ret = 0;
        ds << (qint16)GAME_SERVER_DBQUERY_SUCCESS
           << (qint32)query.numRowsAffected()
           << query.lastInsertId()
           << list
              ;
        emit s_DBQuery(socketContext, ret, "", ba);
        query.finish();
        return ret;
    }
    else
    {
        ret = -1;
        ds << (qint16)GAME_SERVER_DBQUERY_FAIL
           << (qint16)ret;
        emit s_DBQuery(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}


/*int Database::sl_GetPetsInfoToBuffer(quint32 userGameID, QByteArray ba, _SocketInfo::_SocketContext socketContext)
{
    int ret;
    QDataStream ds(&ba,QIODevice::ReadWrite);
    ds.device()->seek(ba.size());
    ds << (qint16)GAME_SERVER_RESPONSE << (qint16)GAME_SERVER_CLIENT << (qint16)GAME_SERVER_CLIENT_PETSINFO;

    if (m_pMysql->connectDB())
    {
        QSqlQuery query(m_pMysql->m_db);  //查询
        QString strQuery = QString("SELECT * FROM lms_game_pet_info WHERE GameUserID=%1")
                .arg(userGameID);

        if(!query.exec(strQuery))
        {
            ret = -2;
            ds << (qint16)GAME_SERVER_CLIENT_PETSINFO_FAIL
               << (qint16)ret;
            emit s_GetPetsInfoToBufferFinished(socketContext, ret
                             , m_pMysql->m_db.lastError().text() + "\r\n" + query.lastError().text() + "\r\n" + strQuery
                             , ba
                             );
            query.finish();
            return ret;
        }

        //quint32 recordCount = 0;
        //int pos = ds.device()->pos();
        //ds << recordCount;

        QVariantList listInfo;

        while(query.next())
        {
            QVariantMap info;
            info["id"] = (quint32)query.value("id").toUInt();
            info["nickname"] = query.value("nick_name").toString();
            listInfo << info;
            //out << (quint32)query.value("WordCount").toUInt();
            //recordCount ++;
        }

        ds << (qint16)GAME_SERVER_CLIENT_PETSINFO_SUCCESS << listInfo;
        //ds.device()->seek(pos);
        //ds << recordCount;

        qDebug() << "[GameServer]共:" << listInfo.count();
        qDebug() << "------------------";


        ret = 0;
        emit s_GetPetsInfoToBufferFinished(socketContext, ret, "", ba);
        query.finish();
        return ret;
    }
    else
    {
        ret = -1;
        ds << (qint16)GAME_SERVER_CLIENT_PETSINFO_FAIL << (qint16)ret;
        emit s_GetPetsInfoToBufferFinished(socketContext, ret, "[!Database]connectDB Error!", ba);
        return ret;
    }
}
*/
